package com.tanhua.manage.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.tanhua.manage.enums.LogTypeEnum;
import com.tanhua.manage.pojo.AnalysisByDay;
import com.tanhua.manage.pojo.Log;
import com.tanhua.manage.pojo.User;
import com.tanhua.manage.service.AnalysisService;
import com.tanhua.manage.service.LogService;
import com.tanhua.manage.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时统计
 * 前面已经将数据写入到tb_log表中，需要使用定时任务，将数据进行统计计算，存储到tb_analysis_by_day表中
 * @author mxk
 * @date 2021/3/29 14:29
 */
@Service
public class AnalysisJob {

    @Autowired
    private AnalysisService analysisService;
    @Autowired
    private LogService logService;
    @Autowired
    private UserService userService;
    /**
     * 用于统计
     */
    @Scheduled(cron = "0 0/30 * * * *")//每30分钟执行一次
    public void run(){
        //record_date` date NOT NULL COMMENT '日期',
        Date today = new Date();
        String todayStr = DateUtil.formatDate(today);
        //查询今天的统计数量  如果今天的还没有就创建
        AnalysisByDay analysisByDay = analysisService.getOne(Wrappers.<AnalysisByDay>lambdaQuery().eq(AnalysisByDay::getRecordDate, todayStr));
        if (analysisByDay==null){
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(today);
            analysisByDay.setCreated(today);
            analysisByDay.setUpdated(today);
            analysisService.save(analysisByDay);
        }

        //查询当日活跃用户数 只要在日志表中有操作记录,就算活跃用户
        int activeCount = logService.count(Wrappers.query(Log.builder()
                .logTime(todayStr).build()).select("DISTINCT(user_id)"));
        if (activeCount>0){
            //num_active` int(8) NOT NULL DEFAULT '0' COMMENT '活跃用户数',
            analysisByDay.setNumActive(activeCount);
        }
        //查询用户登录数据 (不去重)
        List<Log> logList = logService.list(Wrappers.query(Log.builder()
                .logTime(todayStr)
                .type(LogTypeEnum.LOGIN.getValue())
                .build())
        );
        if (CollUtil.isNotEmpty(logList)){
            //今日登录数量
            analysisByDay.setNumLogin(logList.size());

            //统计数据归0 重新计算
            analysisByDay.setNumRegistered(0);
            analysisByDay.setNumRetention1d(0);

            //就算里面有重复的id也没关系
            //根据查询出的登录用户的日志集合得到登录用户的user集合
            ArrayList<User> userArrayList = new ArrayList<>();//今日注册用户
            List<User> userList = userService.list(Wrappers.<User>lambdaQuery().in(User::getId, CollUtil.getFieldValues(logList, "userId")));
            for (User user : userList) {
                long days = DateUtil.betweenDay(user.getCreated(), today, true);
                if (days==0){
                    //今天注册
                    userArrayList.add(user);
                    analysisByDay.setNumRegistered(analysisByDay.getNumRegistered()+1);
                }
            }
            for (User user : userArrayList) {
                Log log = logService.getOne(Wrappers.query(Log.builder()
                        .logTime(DateUtil.offsetDay(today,1).toString())
                        .userId(user.getId())
                        .type(LogTypeEnum.LOGIN.getValue())
                        .build())
                );
                if (log!=null){
                    analysisByDay.setNumRetention1d(analysisByDay.getNumRetention1d()+1);
                }
            }
        }
        //更新数据
        analysisService.updateById(analysisByDay);
    }
}